{-# LANGUAGE DeriveDataTypeable #-}

module Language.Dependencies.Adaptors.Json where

-- container
import Data.Tree (Tree(Node,rootLabel))


-- local imports
import Language.Dependencies.Language
import Language.Dependencies.Term2tree (data2tree)

import Text.HJson
import Generics.MultiRec.Languages.JSON
 
languagejson = Language {
    name=  "Json" 
  , syntax = "js"
  , exts = [".json"] 
  , parse = parseJson
  , toTree = (data2tree TheJson :: Json -> Tree String)
  , srcLoc       = toSrcLoc
  , adjustSrcLoc = Nothing
  , srcLoctype   = (Coordinate undefined undefined) 
  , typerep = Just (TheJson)
  }
    
parseJson :: String -> Either Error Json
parseJson s = case (fromString s) of
   Right json -> Right json
   Left msg   -> Left (ErrMessage msg)

toSrcLoc :: Tree String -> [Loc]
toSrcLoc (Node "SrcSpan" [ srcFrom, srcTo ]  ) = return $ Coordinate (fst $ extract srcFrom, snd $ extract srcFrom) (fst $ extract srcTo, snd $ extract srcTo) 
toSrcLoc _ = []

extract (Node (srcSpan) cs ) = ((read line :: Int),(read column :: Int))
                               where
                                 srcLoc = words srcSpan
                                 line = init (srcLoc !! 2)
                                 column = init (srcLoc !! 4)
